const { app, BrowserWindow, ipcMain, powerMonitor, Notification, dialog, desktopCapturer } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

// // 1. 在 Electron 层面禁用硬件加速
// app.disableHardwareAcceleration();

// // 2. 在 Chromium 层面追加命令行开关，彻底禁用 GPU
// app.commandLine.appendSwitch('disable-gpu');

let mainWindow;
// 保存所有子窗和悬浮窗的引用，防止内存泄漏
const subWindows = new Map();
const floatWindows = new Map();
// 区域选择窗口
let regionSelectWindow = null;
// 浏览器窗口
const browserWindows = new Map();

// 单实例锁，防止从 dock 栏打开新窗口
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  // 如果已经有实例在运行，则退出
  app.quit();
} else {
  // 监听第二个实例启动事件（从 dock 栏右键菜单"打开新窗口"触发）
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 如果主窗口存在，则激活并显示它
    if (mainWindow) {
      if (mainWindow.isMinimized()) {
        mainWindow.restore();
      }
      mainWindow.focus();
      mainWindow.show();
    }
  });
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
      // 允许打印
      enableWebSQL: false,
    },
  });

  mainWindow.loadFile('index.html');

  // 主窗口关闭时清理所有子窗
  mainWindow.on('closed', () => {
    subWindows.forEach((win) => {
      if (!win.isDestroyed()) {
        win.close();
      }
    });
    floatWindows.forEach((win) => {
      if (!win.isDestroyed()) {
        win.close();
      }
    });
    browserWindows.forEach((win) => {
      if (!win.isDestroyed()) {
        win.close();
      }
    });
    subWindows.clear();
    floatWindows.clear();
    browserWindows.clear();
    mainWindow = null;
  });
  
  return mainWindow;
}

// 创建常规子窗
ipcMain.on('create-sub-window', (event) => {
  // 检查主窗口是否存在
  if (!mainWindow || mainWindow.isDestroyed()) {
    console.error('创建子窗失败: 主窗口不可用');
    if (event.reply) {
      event.reply('window-creation-error', 'Main window not available');
    }
    return;
  }

  try {
    const subWindow = new BrowserWindow({
      windowInfo: {
        // type的取值是mainWindow，subWindow，floatWindow
        // 创建常规子窗，同时parent应设置为父窗口引用
        type: 'subWindow'
      },
      width: 400,
      height: 300,
      parent: mainWindow,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
      },
    });
    
    const windowId = subWindow.id;
    subWindows.set(windowId, subWindow);
    
    subWindow.loadFile('sub.html');
    
    // 窗口关闭时清理引用
    subWindow.on('closed', () => {
      subWindows.delete(windowId);
      console.log('子窗已关闭:', windowId);
  });

    // 错误处理
    subWindow.webContents.on('crashed', () => {
      console.error('子窗崩溃:', windowId);
      subWindows.delete(windowId);
  });

    subWindow.webContents.on('render-process-gone', (event, details) => {
      console.error('子窗渲染进程崩溃:', windowId, details);
      subWindows.delete(windowId);
    });
    
    console.log('子窗创建成功:', windowId);
  } catch (error) {
    console.error('创建子窗失败:', error);
    if (event.reply) {
      event.reply('window-creation-error', error.message);
    }
  }
});

// 打印功能
ipcMain.on('print', (event) => {
  console.log('收到打印请求');
  const window = BrowserWindow.fromWebContents(event.sender);
  if (!window) {
    console.error('无法获取窗口对象');
    return;
  }
  
  console.log('准备调用打印 API');
  try {
    // 尝试使用 Electron 的打印 API
    if (window.webContents && typeof window.webContents.print === 'function') {
      window.webContents.print({
        silent: false,
        printBackground: true,
        deviceName: ''
      }, (success, failureReason) => {
        if (success) {
          console.log('打印成功');
        } else {
          console.error('打印失败:', failureReason);
          // 如果 Electron 打印失败，尝试使用浏览器原生打印
          console.log('尝试使用浏览器原生打印');
          window.webContents.executeJavaScript('window.print()').catch(err => {
            console.error('浏览器原生打印也失败:', err);
          });
        }
      });
    } else {
      console.warn('webContents.print 不可用，使用浏览器原生打印');
      window.webContents.executeJavaScript('window.print()').catch(err => {
        console.error('浏览器原生打印失败:', err);
      });
    }
  } catch (error) {
    console.error('打印过程中发生错误:', error);
    // 降级方案：使用浏览器原生打印
    try {
      window.webContents.executeJavaScript('window.print()').catch(err => {
        console.error('降级打印也失败:', err);
      });
    } catch (e) {
      console.error('所有打印方案都失败:', e);
    }
  }
});

// 获取电池电量的辅助函数
async function getBatteryLevel() {
  const platform = process.platform;
  let command = '';
  
  try {
    if (platform === 'win32') {
      // Windows: 使用 WMIC 命令
      command = 'WMIC PATH Win32_Battery Get EstimatedChargeRemaining';
      const { stdout } = await execAsync(command);
      const match = stdout.match(/\d+/);
      if (match) {
        return {
          level: parseInt(match[0], 10),
          charging: null, // Windows WMIC 不直接提供充电状态
          chargingTime: null,
          dischargingTime: null
        };
      }
    } else if (platform === 'darwin') {
      // macOS: 使用 pmset 命令
      command = 'pmset -g batt';
      const { stdout } = await execAsync(command);
      const levelMatch = stdout.match(/(\d+)%/);
      const chargingMatch = stdout.match(/charging|discharging|AC Power/i);
      
      let level = null;
      let charging = null;
      
      if (levelMatch) {
        level = parseInt(levelMatch[1], 10);
      }
      if (chargingMatch) {
        charging = chargingMatch[0].toLowerCase().includes('charging') || 
                   chargingMatch[0].toLowerCase().includes('ac');
      }
      
      return {
        level: level,
        charging: charging,
        chargingTime: null,
        dischargingTime: null
      };
    } else if (platform === 'linux') {
      // Linux: 使用 acpi 命令
      command = 'acpi -b';
      const { stdout } = await execAsync(command);
      const levelMatch = stdout.match(/(\d+)%/);
      const chargingMatch = stdout.match(/Charging|Discharging/i);
      
      let level = null;
      let charging = null;
      
      if (levelMatch) {
        level = parseInt(levelMatch[1], 10);
      }
      if (chargingMatch) {
        charging = chargingMatch[0].toLowerCase().includes('charging');
      }
      
      return {
        level: level,
        charging: charging,
        chargingTime: null,
        dischargingTime: null
      };
    }
  } catch (error) {
    console.error('获取电池电量失败:', error);
    // 返回默认值
    return {
      level: null,
      charging: null,
      chargingTime: null,
      dischargingTime: null,
      error: error.message
    };
  }
  
  // 默认返回值
  return {
    level: null,
    charging: null,
    chargingTime: null,
    dischargingTime: null,
    error: 'Unsupported platform'
  };
}

// 获取电池电量
ipcMain.handle('get-battery-level', async (event) => {
  console.log('收到获取电池电量请求');
  try {
    const batteryInfo = await getBatteryLevel();
    console.log('电池信息:', batteryInfo);
    return batteryInfo;
  } catch (error) {
    console.error('获取电池电量错误:', error);
    return {
      level: null,
      charging: null,
      chargingTime: null,
      dischargingTime: null,
      error: error.message
    };
  }
});

// 获取充电状态
async function getChargingStatus() {
  const platform = process.platform;
  console.log('获取充电状态，平台:', platform);
  
  try {
    // 方法1: 使用Electron的powerMonitor API（最可靠）
    // 注意：powerMonitor.on('on-ac')和on('on-battery')是事件监听，不能直接查询状态
    // 我们需要使用系统命令来获取当前状态
    
    if (platform === 'win32') {
      // Windows: 使用WMIC命令获取电池状态
      try {
        const command = 'WMIC PATH Win32_Battery Get BatteryStatus,ChargeStatus';
        const { stdout } = await execAsync(command);
        
        // BatteryStatus: 2 = 充电中, 3 = 放电中, 其他 = 未知
        // ChargeStatus: 1 = 充电中, 2 = 放电中, 其他 = 未知
        const batteryStatusMatch = stdout.match(/BatteryStatus\s+(\d+)/i);
        const chargeStatusMatch = stdout.match(/ChargeStatus\s+(\d+)/i);
        
        let isCharging = null;
        if (batteryStatusMatch) {
          const status = parseInt(batteryStatusMatch[1], 10);
          isCharging = status === 2; // 2表示充电中
        } else if (chargeStatusMatch) {
          const status = parseInt(chargeStatusMatch[1], 10);
          isCharging = status === 1; // 1表示充电中
        }
        
        // 如果无法从电池状态判断，尝试检查AC电源状态
        if (isCharging === null) {
          try {
            const acCommand = 'powercfg /getactivescheme';
            // Windows没有直接命令检查AC状态，使用powerMonitor事件状态
            // 这里我们使用系统命令检查电源方案
            const { stdout: acOutput } = await execAsync('powercfg /list');
            // 如果系统有电池，尝试其他方法
            isCharging = null; // 无法确定
          } catch (error) {
            console.warn('检查AC电源状态失败:', error.message);
          }
        }
        
        return {
          isCharging: isCharging,
          platform: 'Windows',
          method: 'WMIC'
        };
      } catch (error) {
        console.warn('使用WMIC获取充电状态失败:', error.message);
      }
    } else if (platform === 'darwin') {
      // macOS: 使用pmset命令
      try {
        const command = 'pmset -g batt';
        const { stdout } = await execAsync(command);
        
        const chargingMatch = stdout.match(/charging|discharging|AC Power|Battery Power/i);
        let isCharging = null;
        
        if (chargingMatch) {
          const status = chargingMatch[0].toLowerCase();
          isCharging = status.includes('charging') || status.includes('ac power');
        }
        
        return {
          isCharging: isCharging,
          platform: 'macOS',
          method: 'pmset'
        };
      } catch (error) {
        console.warn('使用pmset获取充电状态失败:', error.message);
      }
    } else if (platform === 'linux') {
      // Linux: 使用acpi命令或/sys/class/power_supply
      try {
        // 方法1: 使用acpi命令
        const command = 'acpi -b';
        const { stdout } = await execAsync(command);
        
        const chargingMatch = stdout.match(/Charging|Discharging|Full/i);
        let isCharging = null;
        
        if (chargingMatch) {
          const status = chargingMatch[0].toLowerCase();
          isCharging = status.includes('charging') || status.includes('full');
        }
        
        if (isCharging !== null) {
          return {
            isCharging: isCharging,
            platform: 'Linux',
            method: 'acpi'
          };
        }
      } catch (error) {
        console.warn('使用acpi获取充电状态失败:', error.message);
      }
      
      // 方法2: 读取/sys/class/power_supply（Linux/鸿蒙PC）
      try {
        const powerSupplyPath = '/sys/class/power_supply';
        
        if (fs.existsSync(powerSupplyPath)) {
          const dirs = fs.readdirSync(powerSupplyPath);
          
          for (const dir of dirs) {
            const statusPath = `${powerSupplyPath}/${dir}/status`;
            if (fs.existsSync(statusPath)) {
              const status = fs.readFileSync(statusPath, 'utf8').trim().toLowerCase();
              if (status === 'charging' || status === 'full') {
                return {
                  isCharging: true,
                  platform: 'Linux/HarmonyOS PC',
                  method: 'sysfs',
                  source: dir
                };
              } else if (status === 'discharging') {
                return {
                  isCharging: false,
                  platform: 'Linux/HarmonyOS PC',
                  method: 'sysfs',
                  source: dir
                };
              }
            }
          }
        }
      } catch (error) {
        console.warn('使用sysfs获取充电状态失败:', error.message);
      }
    }
    
    // 如果所有方法都失败，返回未知状态
    return {
      isCharging: null,
      platform: platform,
      method: 'unknown',
      error: 'Unable to determine charging status'
    };
  } catch (error) {
    console.error('获取充电状态失败:', error);
    return {
      isCharging: null,
      platform: platform,
      error: error.message
    };
  }
}

// 获取充电状态
ipcMain.handle('get-charging-status', async (event) => {
  console.log('收到获取充电状态请求');
  try {
    const chargingStatus = await getChargingStatus();
    console.log('充电状态:', chargingStatus);
    return chargingStatus;
  } catch (error) {
    console.error('获取充电状态错误:', error);
    return {
      isCharging: null,
      platform: process.platform,
      error: error.message
    };
  }
});

// 监听电源状态变化
powerMonitor.on('on-ac', () => {
  console.log('电源已连接');
  // 通知所有窗口电源状态变化
  BrowserWindow.getAllWindows().forEach(win => {
    if (!win.isDestroyed()) {
      win.webContents.send('battery-status-changed', {
        charging: true,
        level: null // 需要重新获取
      });
      // 发送充电状态变化事件
      win.webContents.send('charging-status-changed', {
        isCharging: true
      });
    }
  });
});

powerMonitor.on('on-battery', () => {
  console.log('使用电池供电');
  // 通知所有窗口电源状态变化
  BrowserWindow.getAllWindows().forEach(win => {
    if (!win.isDestroyed()) {
      win.webContents.send('battery-status-changed', {
        charging: false,
        level: null // 需要重新获取
      });
      // 发送充电状态变化事件
      win.webContents.send('charging-status-changed', {
        isCharging: false
      });
    }
  });
});

// 存储通知实例，用于后续关闭
const notifications = new Map();

// 显示通知
ipcMain.handle('show-notification', async (event, options) => {
  console.log('收到显示通知请求:', options);
  
  // 检查通知权限
  if (!Notification.isSupported()) {
    console.warn('当前系统不支持通知功能');
    return { success: false, error: 'Notifications not supported' };
  }

  try {
    // macOS 特殊处理：检查系统通知权限
    if (process.platform === 'darwin') {
      // macOS 上 Electron 的 Notification 不需要额外权限请求
      // 但需要确保应用在 Dock 中（通常 Electron 应用会自动处理）
      console.log('macOS 平台，准备显示通知');
    }

    // 创建通知选项（根据平台调整）
    const notificationOptions = {
      title: options.title || '通知',
      body: options.body || options.message || '',
      silent: options.silent || false
    };

    // macOS 特殊选项
    if (process.platform === 'darwin') {
      // macOS 支持 subtitle
      if (options.subtitle) {
        notificationOptions.subtitle = options.subtitle;
      }
      // macOS 支持 sound（使用系统默认声音）
      if (options.sound !== false) {
        notificationOptions.sound = options.sound || 'default';
      }
      // macOS 支持 urgency（但可能被系统忽略）
      if (options.urgency) {
        notificationOptions.urgency = options.urgency;
      }
              } else {
      // Linux/Windows 选项
      notificationOptions.icon = options.icon || undefined;
      notificationOptions.urgency = options.urgency || 'normal';
      notificationOptions.timeoutType = options.timeoutType || 'default';
      if (options.actions && options.actions.length > 0) {
        notificationOptions.actions = options.actions;
      }
      if (options.closeButtonText) {
        notificationOptions.closeButtonText = options.closeButtonText;
      }
      if (options.hasReply) {
        notificationOptions.hasReply = options.hasReply;
        notificationOptions.replyPlaceholder = options.replyPlaceholder;
      }
    }

    console.log('创建通知，选项:', JSON.stringify(notificationOptions, null, 2));

    // 创建通知
    let notification;
    try {
      notification = new Notification(notificationOptions);
      console.log('通知对象创建成功');
    } catch (error) {
      console.error('创建通知对象失败:', error);
      throw error;
    }

    // 生成通知ID
    const notificationId = options.notificationId || Date.now();

    // 监听通知点击事件
    notification.on('click', () => {
      console.log('通知被点击:', notificationId);
      // 通知所有窗口
            BrowserWindow.getAllWindows().forEach(win => {
        if (!win.isDestroyed()) {
          win.webContents.send('notification-clicked', notificationId);
        }
      });
      
      // 如果指定了点击回调，激活窗口
      if (options.onClick !== false && mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.show();
        mainWindow.focus();
      }
    });

    // 监听通知关闭事件
    notification.on('close', () => {
      console.log('通知已关闭:', notificationId);
      notifications.delete(notificationId);
    });

    // 监听通知显示事件
    notification.on('show', () => {
      console.log('✅ 通知已显示:', notificationId);
      console.log('通知标题:', notificationOptions.title);
      console.log('通知内容:', notificationOptions.body);
    });
    
    // 监听通知错误事件
    notification.on('error', (error) => {
      console.error('❌ 通知错误:', notificationId, error);
      console.error('错误详情:', error.message);
    });

    // 监听操作按钮点击事件（如果支持，非 macOS）
    if (process.platform !== 'darwin' && notificationOptions.actions && notificationOptions.actions.length > 0) {
      notification.on('action', (event, index) => {
        console.log('通知操作按钮被点击:', notificationId, index);
            BrowserWindow.getAllWindows().forEach(win => {
          if (!win.isDestroyed()) {
            win.webContents.send('notification-action-clicked', {
              notificationId: notificationId,
              actionIndex: index
            });
          }
        });
      });
    }

    // macOS 上，通知创建后需要调用 show() 才能显示
    // 其他平台也必须调用 show()
    try {
      // 确保在主线程中调用 show()
      notification.show();
      console.log('通知 show() 调用成功');
      
      // macOS 上，有时需要稍微延迟才能看到通知
      // 但 show() 调用本身应该是同步的
      if (process.platform === 'darwin') {
        console.log('macOS 通知已调用 show()，应该会显示在通知中心');
      }
    } catch (error) {
      console.error('通知 show() 调用失败:', error);
      console.error('错误详情:', error.stack);
      // 即使 show() 失败，也返回成功（某些情况下通知可能仍然会显示）
      if (process.platform !== 'darwin') {
        // 非 macOS 平台，show() 失败是严重错误
        throw error;
      }
    }

    // 存储通知实例（防止被垃圾回收）
    notifications.set(notificationId, notification);
    
    // 添加超时清理（5分钟后自动清理）
    setTimeout(() => {
      if (notifications.has(notificationId)) {
        notifications.delete(notificationId);
        console.log('通知实例已清理:', notificationId);
      }
    }, 5 * 60 * 1000);

    console.log('通知处理完成，ID:', notificationId);
    return { success: true, notificationId: notificationId };
  } catch (error) {
    console.error('显示通知失败:', error);
    return { success: false, error: error.message };
  }
});

// 关闭通知
ipcMain.on('close-notification', (event, notificationId) => {
  console.log('收到关闭通知请求:', notificationId);
  const notification = notifications.get(notificationId);
  if (notification) {
    notification.close();
    notifications.delete(notificationId);
  } else {
    console.warn('通知不存在:', notificationId);
  }
});

// 选择单个文件
ipcMain.handle('select-file', async (event, options = {}) => {
  console.log('收到选择文件请求:', options);
  
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: options.title || '选择文件',
      defaultPath: options.defaultPath || app.getPath('documents'),
      buttonLabel: options.buttonLabel || '选择',
      filters: options.filters || [
        { name: '所有文件', extensions: ['*'] }
      ],
      properties: [
        'openFile',
        ...(options.allowMultiple ? ['multiSelections'] : [])
      ]
    });

    if (result.canceled) {
      console.log('用户取消了文件选择');
      return { canceled: true, filePaths: [] };
    }

    console.log('选择的文件:', result.filePaths);
    return { canceled: false, filePaths: result.filePaths };
  } catch (error) {
    console.error('选择文件失败:', error);
    return { canceled: true, error: error.message, filePaths: [] };
  }
});

// 选择多个文件
ipcMain.handle('select-files', async (event, options = {}) => {
  console.log('收到选择多个文件请求:', options);
  
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: options.title || '选择文件',
      defaultPath: options.defaultPath || app.getPath('documents'),
      buttonLabel: options.buttonLabel || '选择',
      filters: options.filters || [
        { name: '所有文件', extensions: ['*'] }
      ],
      properties: ['openFile', 'multiSelections']
    });

    if (result.canceled) {
      console.log('用户取消了文件选择');
      return { canceled: true, filePaths: [] };
    }

    console.log('选择的文件:', result.filePaths);
    return { canceled: false, filePaths: result.filePaths };
  } catch (error) {
    console.error('选择文件失败:', error);
    return { canceled: true, error: error.message, filePaths: [] };
  }
});

// 选择文件夹
ipcMain.handle('select-folder', async (event, options = {}) => {
  console.log('收到选择文件夹请求:', options);
  
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: options.title || '选择文件夹',
      defaultPath: options.defaultPath || app.getPath('documents'),
      buttonLabel: options.buttonLabel || '选择',
      properties: ['openDirectory', ...(options.allowMultiple ? ['multiSelections'] : [])]
    });

    if (result.canceled) {
      console.log('用户取消了文件夹选择');
      return { canceled: true, filePaths: [] };
    }

    console.log('选择的文件夹:', result.filePaths);
    return { canceled: false, filePaths: result.filePaths };
  } catch (error) {
    console.error('选择文件夹失败:', error);
    return { canceled: true, error: error.message, filePaths: [] };
  }
});

// 保存文件
ipcMain.handle('save-file', async (event, options = {}) => {
  console.log('收到保存文件请求:', options);
  
  try {
    const result = await dialog.showSaveDialog(mainWindow, {
      title: options.title || '保存文件',
      defaultPath: options.defaultPath || app.getPath('documents'),
      buttonLabel: options.buttonLabel || '保存',
      filters: options.filters || [
        { name: '所有文件', extensions: ['*'] }
      ]
    });

    if (result.canceled) {
      console.log('用户取消了保存文件');
      return { canceled: true, filePath: null };
    }

    console.log('保存文件路径:', result.filePath);
    
    // 如果提供了文件内容，自动写入文件
    if (options.content !== undefined) {
      try {
        fs.writeFileSync(result.filePath, options.content, options.encoding || 'utf8');
        console.log('文件已保存:', result.filePath);
        return { canceled: false, filePath: result.filePath, saved: true };
      } catch (writeError) {
        console.error('写入文件失败:', writeError);
        return { canceled: false, filePath: result.filePath, saved: false, error: writeError.message };
      }
    }

    return { canceled: false, filePath: result.filePath, saved: false };
  } catch (error) {
    console.error('保存文件失败:', error);
    return { canceled: true, error: error.message, filePath: null };
  }
});

// 读取文件内容
ipcMain.handle('read-file', async (event, filePath, encoding = 'utf8') => {
  console.log('收到读取文件请求:', filePath);
  
  try {
    if (!fs.existsSync(filePath)) {
      return { success: false, error: '文件不存在' };
    }

    const stats = fs.statSync(filePath);
    if (!stats.isFile()) {
      return { success: false, error: '路径不是文件' };
    }

    const content = fs.readFileSync(filePath, encoding);
    return { success: true, content: content, size: stats.size };
  } catch (error) {
    console.error('读取文件失败:', error);
    return { success: false, error: error.message };
  }
});

// 保存图片（从base64数据）
// 保存音频文件
ipcMain.handle('save-audio', async (event, base64Data, defaultFileName, mimeType) => {
  console.log('收到保存音频请求');
  
  try {
    // 根据MIME类型确定文件扩展名
    let defaultExt = 'webm';
    if (mimeType) {
      if (mimeType.includes('webm')) {
        defaultExt = 'webm';
      } else if (mimeType.includes('ogg')) {
        defaultExt = 'ogg';
      } else if (mimeType.includes('mp4')) {
        defaultExt = 'm4a';
      } else if (mimeType.includes('wav')) {
        defaultExt = 'wav';
      }
    }
    
    // 确保文件名有正确的扩展名
    let fileName = defaultFileName || `recording-${Date.now()}.${defaultExt}`;
    if (!fileName.endsWith(`.${defaultExt}`) && !fileName.match(/\.(webm|ogg|m4a|wav|mp3)$/i)) {
      fileName = fileName.replace(/\.[^.]*$/, '') + `.${defaultExt}`;
    }
    
    // 显示保存对话框
    const result = await dialog.showSaveDialog(mainWindow, {
      title: '保存录音',
      defaultPath: fileName,
      buttonLabel: '保存',
      filters: [
        { name: '音频文件', extensions: ['webm', 'ogg', 'm4a', 'wav', 'mp3'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    });

    if (result.canceled) {
      console.log('用户取消了保存音频');
      return { canceled: true, filePath: null };
    }

    console.log('保存音频路径:', result.filePath);
    
    // 将Base64数据转换为Buffer
    const buffer = Buffer.from(base64Data, 'base64');
    
    // 写入文件
    fs.writeFileSync(result.filePath, buffer);
    console.log('音频文件已保存:', result.filePath);
    
    return { canceled: false, filePath: result.filePath, saved: true };
  } catch (error) {
    console.error('保存音频文件失败:', error);
    return { canceled: false, filePath: null, saved: false, error: error.message };
  }
});

ipcMain.handle('save-image', async (event, base64Data, defaultFileName) => {
  console.log('收到保存图片请求');
  
  try {
    // 显示保存对话框
    const result = await dialog.showSaveDialog(mainWindow, {
      title: '保存照片',
      defaultPath: defaultFileName || `photo-${Date.now()}.png`,
      buttonLabel: '保存',
      filters: [
        { name: '图片文件', extensions: ['png', 'jpg', 'jpeg'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    });

    if (result.canceled) {
      console.log('用户取消了保存图片');
      return { canceled: true, filePath: null };
    }

    console.log('保存图片路径:', result.filePath);
    
    try {
      // 将base64数据转换为Buffer
      const base64Content = base64Data.replace(/^data:image\/\w+;base64,/, '');
      const buffer = Buffer.from(base64Content, 'base64');
      
      // 写入文件
      fs.writeFileSync(result.filePath, buffer);
      console.log('图片已保存:', result.filePath);
      return { canceled: false, filePath: result.filePath, saved: true };
    } catch (writeError) {
      console.error('写入图片失败:', writeError);
      return { canceled: false, filePath: result.filePath, saved: false, error: writeError.message };
    }
  } catch (error) {
    console.error('保存图片失败:', error);
    return { canceled: true, error: error.message, filePath: null };
  }
});

// 捕获当前窗口截图
ipcMain.handle('capture-window', async (event) => {
  console.log('收到捕获窗口截图请求');
  
  try {
    if (!mainWindow || mainWindow.isDestroyed()) {
      return { success: false, error: '主窗口不可用' };
    }
    
    // 使用webContents.capturePage()捕获当前窗口
    const image = await mainWindow.webContents.capturePage();
    
    // 转换为PNG格式的Buffer
    const buffer = image.toPNG();
    
    // 转换为base64
    const base64 = buffer.toString('base64');
    const dataUrl = `data:image/png;base64,${base64}`;
    
    console.log('窗口截图已捕获，尺寸:', image.getSize());
    
    return {
      success: true,
      dataUrl: dataUrl,
      width: image.getSize().width,
      height: image.getSize().height
    };
  } catch (error) {
    console.error('捕获窗口截图失败:', error);
    return { success: false, error: error.message };
  }
});

// 获取可用的屏幕源（用于全屏截图）
ipcMain.handle('get-screen-sources', async (event) => {
  console.log('收到获取屏幕源请求');
  
  try {
    const sources = await desktopCapturer.getSources({
      types: ['screen', 'window'],
      thumbnailSize: { width: 0, height: 0 }
    });
    
    console.log('可用的屏幕源数量:', sources.length);
    
    return {
      success: true,
      sources: sources.map(source => ({
        id: source.id,
        name: source.name,
        thumbnail: source.thumbnail.toDataURL()
      }))
    };
  } catch (error) {
    console.error('获取屏幕源失败:', error);
    return { success: false, error: error.message };
  }
});

// 捕获屏幕截图
ipcMain.handle('capture-screen', async (event, sourceId) => {
  console.log('收到捕获屏幕截图请求，源ID:', sourceId);
  
  try {
    // 获取屏幕源，设置较大的thumbnailSize以获取高质量截图
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { width: 1920, height: 1080 } // 设置较大的尺寸以获取高质量截图
    });
    
    let targetSource = null;
    if (sourceId) {
      targetSource = sources.find(s => s.id === sourceId);
    }
    
    // 如果没有指定源ID或找不到，使用第一个屏幕源
    if (!targetSource && sources.length > 0) {
      targetSource = sources[0];
    }
    
    if (!targetSource) {
      return { success: false, error: '未找到可用的屏幕源' };
    }
    
    // 获取屏幕缩略图（NativeImage对象）
    const thumbnail = targetSource.thumbnail;
    
    // 转换为PNG格式的Buffer，然后转为base64
    const buffer = thumbnail.toPNG();
    const base64 = buffer.toString('base64');
    const dataUrl = `data:image/png;base64,${base64}`;
    
    const size = thumbnail.getSize();
    console.log('屏幕截图已捕获，源:', targetSource.name, '尺寸:', size.width, 'x', size.height);
    
    return {
      success: true,
      dataUrl: dataUrl,
      width: size.width,
      height: size.height,
      sourceName: targetSource.name
    };
  } catch (error) {
    console.error('捕获屏幕截图失败:', error);
    return { success: false, error: error.message };
  }
});

// 启动区域选择截图
ipcMain.handle('start-region-select', async (event) => {
  console.log('收到启动区域选择截图请求');
  
  try {
    // 如果已有区域选择窗口，先关闭
    if (regionSelectWindow && !regionSelectWindow.isDestroyed()) {
      regionSelectWindow.close();
    }
    
    // 先获取屏幕截图作为背景
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { width: 0, height: 0 } // 获取全分辨率
    });
    
    if (sources.length === 0) {
      return { success: false, error: '未找到可用的屏幕源' };
    }
    
    const screenSource = sources[0];
    const thumbnail = screenSource.thumbnail;
    const screenSize = thumbnail.getSize();
    
    // 转换为base64用于显示
    const buffer = thumbnail.toPNG();
    const base64 = buffer.toString('base64');
    const screenDataUrl = `data:image/png;base64,${base64}`;
    
    // 获取所有显示器的信息
    const { screen } = require('electron');
    const displays = screen.getAllDisplays();
    const primaryDisplay = screen.getPrimaryDisplay();
    
    // 创建全屏透明窗口用于区域选择
    regionSelectWindow = new BrowserWindow({
      width: primaryDisplay.workAreaSize.width,
      height: primaryDisplay.workAreaSize.height,
      x: primaryDisplay.workArea.x,
      y: primaryDisplay.workArea.y,
      frame: false,
      transparent: true,
      alwaysOnTop: true,
      skipTaskbar: true,
      resizable: false,
      movable: false,
      minimizable: false,
      maximizable: false,
      closable: false,
      fullscreen: false,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
      },
    });
    
    // 设置窗口在所有显示器上全屏
    regionSelectWindow.setFullScreen(true);
    regionSelectWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
    
    // 加载区域选择页面
    await regionSelectWindow.loadFile(path.join(__dirname, 'region-select.html'));
    
    // 等待页面加载完成后发送屏幕数据
    regionSelectWindow.webContents.once('did-finish-load', () => {
      regionSelectWindow.webContents.send('region-select-init', {
        screenDataUrl: screenDataUrl,
        screenWidth: screenSize.width,
        screenHeight: screenSize.height,
        displayWidth: primaryDisplay.workAreaSize.width,
        displayHeight: primaryDisplay.workAreaSize.height
      });
    });
    
    // 显示窗口
    regionSelectWindow.show();
    regionSelectWindow.focus();
    
    // 监听窗口关闭
    regionSelectWindow.on('closed', () => {
      regionSelectWindow = null;
    });
    
    return {
      success: true,
      screenWidth: screenSize.width,
      screenHeight: screenSize.height
    };
  } catch (error) {
    console.error('启动区域选择失败:', error);
    if (regionSelectWindow && !regionSelectWindow.isDestroyed()) {
      regionSelectWindow.close();
    }
    return { success: false, error: error.message };
  }
});

// 完成区域选择，返回选中区域
ipcMain.handle('complete-region-select', async (event, region) => {
  console.log('收到完成区域选择请求，区域:', region);
  
  try {
    // 关闭区域选择窗口
    if (regionSelectWindow && !regionSelectWindow.isDestroyed()) {
      regionSelectWindow.close();
      regionSelectWindow = null;
    }
    
    // 获取屏幕截图
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { width: 0, height: 0 } // 获取全分辨率
    });
    
    if (sources.length === 0) {
      return { success: false, error: '未找到可用的屏幕源' };
    }
    
    const screenSource = sources[0];
    const thumbnail = screenSource.thumbnail;
    
    // 裁剪选中区域
    const { x, y, width, height } = region;
    const croppedImage = thumbnail.crop({ x, y, width, height });
    
    // 转换为PNG格式的Buffer，然后转为base64
    const buffer = croppedImage.toPNG();
    const base64 = buffer.toString('base64');
    const dataUrl = `data:image/png;base64,${base64}`;
    
    console.log('区域截图已捕获，尺寸:', width, 'x', height);
    
    // 通知主窗口区域选择完成
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('region-selected', {
        success: true,
        dataUrl: dataUrl,
        width: width,
        height: height,
        x: x,
        y: y
      });
    }
    
    return {
      success: true,
      dataUrl: dataUrl,
      width: width,
      height: height,
      x: x,
      y: y
    };
  } catch (error) {
    console.error('完成区域选择失败:', error);
    // 通知主窗口错误
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('region-selected', {
        success: false,
        error: error.message
      });
    }
    return { success: false, error: error.message };
  }
});

// 取消区域选择
ipcMain.handle('cancel-region-select', async (event) => {
  console.log('收到取消区域选择请求');
  
  if (regionSelectWindow && !regionSelectWindow.isDestroyed()) {
    regionSelectWindow.close();
    regionSelectWindow = null;
  }
  
  return { success: true };
});

// 获取WiFi信息（已注释）
/*
async function getWiFiInfo() {
  const platform = process.platform;
  console.log('获取WiFi信息，平台:', platform);
  
  try {
    if (platform === 'win32') {
      // Windows: 使用 netsh wlan show interfaces
      const command = 'netsh wlan show interfaces';
      const { stdout } = await execAsync(command);
      
      // 解析输出
      const ssidMatch = stdout.match(/SSID\s*:\s*(.+)/i);
      const bssidMatch = stdout.match(/BSSID\s*:\s*([0-9a-fA-F:]+)/i);
      const signalMatch = stdout.match(/Signal\s*:\s*(\d+)%/i);
      const radioTypeMatch = stdout.match(/Radio type\s*:\s*(.+)/i);
      const channelMatch = stdout.match(/Channel\s*:\s*(\d+)/i);
      const stateMatch = stdout.match(/State\s*:\s*(.+)/i);
      
      return {
        ssid: ssidMatch ? ssidMatch[1].trim() : null,
        bssid: bssidMatch ? bssidMatch[1].trim() : null,
        signal: signalMatch ? parseInt(signalMatch[1], 10) : null,
        radioType: radioTypeMatch ? radioTypeMatch[1].trim() : null,
        channel: channelMatch ? parseInt(channelMatch[1], 10) : null,
        state: stateMatch ? stateMatch[1].trim() : null,
        platform: 'Windows'
      };
    } else if (platform === 'darwin') {
      // macOS: 使用多种方法获取WiFi信息
      let ssid = null;
      let bssid = null;
      let signal = null;
      let channel = null;
      
      // 方法1: 优先使用 airport 命令（最可靠）
      try {
        const airportCommand = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I';
        const { stdout: airportOutput } = await execAsync(airportCommand);
        console.log('airport命令输出:', airportOutput);
        
        // 提取SSID
        const ssidMatch = airportOutput.match(/^\s*SSID:\s*(.+)$/im);
        if (ssidMatch) {
          ssid = ssidMatch[1].trim();
          console.log('从airport获取到SSID:', ssid);
        }
        
        // 提取BSSID
        const bssidMatch = airportOutput.match(/^\s*BSSID:\s*([0-9a-fA-F:]+)$/im);
        if (bssidMatch) {
          bssid = bssidMatch[1].trim();
          console.log('从airport获取到BSSID:', bssid);
        }
        
        // 提取信号强度
        const rssiMatch = airportOutput.match(/^\s*agrCtlRSSI:\s*([-\d]+)$/im);
        if (rssiMatch) {
          const rssi = parseInt(rssiMatch[1], 10);
          // 将RSSI转换为百分比（-100到0映射到0到100）
          signal = Math.max(0, Math.min(100, 100 + rssi));
          console.log('从airport获取到信号强度:', signal, 'RSSI:', rssi);
        }
        
        // 提取频道
        const channelMatch = airportOutput.match(/^\s*channel:\s*(\d+)/im);
        if (channelMatch) {
          channel = parseInt(channelMatch[1], 10);
          console.log('从airport获取到频道:', channel);
        }
      } catch (error) {
        console.warn('使用airport命令获取WiFi信息失败:', error.message);
      }
      
      // 方法2: 如果airport失败，使用 networksetup 获取SSID
      if (!ssid) {
        try {
          // 首先尝试获取WiFi接口名称
          let interfaceName = null;
          try {
            const interfacesCommand = 'networksetup -listallhardwareports | grep -A 1 "Wi-Fi" | grep "Device" | awk \'{print $2}\'';
            const { stdout: interfaceOutput } = await execAsync(interfacesCommand, { shell: '/bin/bash' });
            interfaceName = interfaceOutput.trim();
            console.log('检测到WiFi接口:', interfaceName);
          } catch (error) {
            console.warn('获取WiFi接口名称失败:', error.message);
          }
          
          // 如果没有找到接口，尝试常见的接口名称
          const interfacesToTry = interfaceName ? [interfaceName] : ['en0', 'en1', 'en2'];
          
          for (const ifName of interfacesToTry) {
            try {
              const ssidCommand = `networksetup -getairportnetwork ${ifName}`;
              const { stdout: ssidOutput } = await execAsync(ssidCommand);
              console.log(`networksetup输出 (${ifName}):`, ssidOutput);
              
              // 尝试多种匹配模式
              let ssidMatch = ssidOutput.match(/Current Wi-Fi Network:\s*(.+)/i);
              if (ssidMatch) {
                ssid = ssidMatch[1].trim();
                console.log('从networksetup获取到SSID:', ssid);
                break;
  } else {
                // 如果没有"Current Wi-Fi Network:"前缀，直接取第一行非空内容
                const lines = ssidOutput.split('\n').filter(line => line.trim());
                if (lines.length > 0) {
                  const firstLine = lines[0].trim();
                  // 排除错误信息
                  if (!firstLine.toLowerCase().includes('error') && 
                      !firstLine.toLowerCase().includes('not associated') &&
                      !firstLine.toLowerCase().includes('you are not associated')) {
                    ssid = firstLine;
                    console.log('从networksetup获取到SSID (第一行):', ssid);
                    break;
                  }
                }
              }
            } catch (error) {
              console.warn(`使用${ifName}获取SSID失败:`, error.message);
              continue;
            }
          }
        } catch (error) {
          console.warn('获取SSID失败:', error.message);
        }
      }
      
      // 方法3: 使用 system_profiler 获取详细WiFi信息（作为补充）
      try {
        const infoCommand = 'system_profiler SPAirPortDataType';
        const { stdout: infoOutput } = await execAsync(infoCommand);
        console.log('system_profiler输出长度:', infoOutput.length);
        
        // 从system_profiler中提取SSID（如果前面都失败）
        if (!ssid) {
          const ssidMatch = infoOutput.match(/Current Network Information:[\s\S]*?Network Name:\s*(.+)/i);
          if (ssidMatch) {
            ssid = ssidMatch[1].trim();
            console.log('从system_profiler获取到SSID:', ssid);
          }
        }
        
        // 提取BSSID（如果airport失败）
        if (!bssid) {
          const bssidMatch = infoOutput.match(/MAC Address:\s*([0-9a-fA-F:]+)/i);
          if (bssidMatch) {
            bssid = bssidMatch[1].trim();
            console.log('从system_profiler获取到BSSID:', bssid);
          }
        }
        
        // 提取信号强度（如果airport失败）
        if (!signal) {
          const signalMatch = infoOutput.match(/Signal:\s*([-\d]+)/i);
          if (signalMatch) {
            const rssi = parseInt(signalMatch[1], 10);
            signal = Math.max(0, Math.min(100, 100 + rssi));
            console.log('从system_profiler获取到信号强度:', signal);
          }
        }
        
        // 提取频道（如果airport失败）
        if (!channel) {
          const channelMatch = infoOutput.match(/Channel:\s*(\d+)/i);
          if (channelMatch) {
            channel = parseInt(channelMatch[1], 10);
            console.log('从system_profiler获取到频道:', channel);
          }
        }
      } catch (error) {
        console.warn('获取WiFi详细信息失败:', error.message);
      }
      
      console.log('最终WiFi信息:', { ssid, bssid, signal, channel });
      
      return {
        ssid: ssid,
        bssid: bssid,
        signal: signal,
        channel: channel,
        platform: 'macOS'
      };
    } else if (platform === 'linux') {
      // Linux: 使用 nmcli 或 iwconfig
      let ssid = null;
      let bssid = null;
      let signal = null;
      let channel = null;
      
      try {
        // 优先使用 nmcli（NetworkManager）
        const command = 'nmcli -t -f active,ssid,bssid,signal,chan device wifi';
        const { stdout } = await execAsync(command);
        const lines = stdout.split('\n').filter(line => line.trim());
        
        for (const line of lines) {
          const parts = line.split(':');
          if (parts[0] === 'yes' && parts.length >= 5) {
            ssid = parts[1] || null;
            bssid = parts[2] || null;
            signal = parts[3] ? parseInt(parts[3], 10) : null;
            channel = parts[4] ? parseInt(parts[4], 10) : null;
            break;
          }
        }
      } catch (error) {
        console.warn('使用nmcli获取WiFi信息失败，尝试iwconfig:', error.message);
        
        try {
          // 降级到 iwconfig
          const command = 'iwconfig 2>/dev/null | grep -E "ESSID|Access Point|Signal level|Frequency"';
          const { stdout } = await execAsync(command, { shell: '/bin/bash' });
          
          const ssidMatch = stdout.match(/ESSID:"([^"]+)"/i);
          const bssidMatch = stdout.match(/Access Point:\s*([0-9a-fA-F:]+)/i);
          const signalMatch = stdout.match(/Signal level=([-\d]+)/i);
          const freqMatch = stdout.match(/Frequency:([\d.]+)/i);
          
          if (ssidMatch) ssid = ssidMatch[1];
          if (bssidMatch) bssid = bssidMatch[1].trim();
          if (signalMatch) signal = parseInt(signalMatch[1], 10);
          if (freqMatch) {
            // 频率转频道（简化计算，2.4GHz和5GHz）
            const freq = parseFloat(freqMatch[1]);
            if (freq >= 2.4 && freq < 2.5) {
              channel = Math.round((freq - 2.412) / 0.005);
            } else if (freq >= 5.0 && freq < 6.0) {
              channel = Math.round((freq - 5.0) / 0.005);
            }
          }
        } catch (error2) {
          console.warn('使用iwconfig获取WiFi信息也失败:', error2.message);
        }
      }
      
      return {
        ssid: ssid,
        bssid: bssid,
        signal: signal,
        channel: channel,
        platform: 'Linux'
      };
  } else {
      // 其他平台（包括鸿蒙PC），尝试通用方法
      console.log('未知平台，尝试通用方法获取WiFi信息');
      
      // 鸿蒙PC可能使用Linux命令，尝试nmcli
      try {
        const command = 'nmcli -t -f active,ssid,bssid,signal,chan device wifi';
        const { stdout } = await execAsync(command);
        const lines = stdout.split('\n').filter(line => line.trim());
        
        for (const line of lines) {
          const parts = line.split(':');
          if (parts[0] === 'yes' && parts.length >= 5) {
            return {
              ssid: parts[1] || null,
              bssid: parts[2] || null,
              signal: parts[3] ? parseInt(parts[3], 10) : null,
              channel: parts[4] ? parseInt(parts[4], 10) : null,
              platform: 'HarmonyOS PC'
            };
          }
        }
      } catch (error) {
        console.warn('通用方法获取WiFi信息失败:', error.message);
      }
      
      return {
        ssid: null,
        bssid: null,
        signal: null,
        channel: null,
        platform: platform,
        error: 'Unsupported platform or no WiFi connection'
      };
    }
  } catch (error) {
    console.error('获取WiFi信息失败:', error);
    return {
      ssid: null,
      bssid: null,
      signal: null,
      channel: null,
      platform: platform,
      error: error.message
    };
  }
}
*/

// 获取WiFi信息（已注释）
/*
ipcMain.handle('get-wifi-info', async (event) => {
  console.log('收到获取WiFi信息请求');
  try {
    const wifiInfo = await getWiFiInfo();
    console.log('WiFi信息:', wifiInfo);
    return wifiInfo;
  } catch (error) {
    console.error('获取WiFi信息错误:', error);
    return {
      ssid: null,
      bssid: null,
      signal: null,
      channel: null,
      platform: process.platform,
      error: error.message
    };
  }
});
*/

// 获取IP地址
async function getIPAddresses() {
  const platform = process.platform;
  console.log('获取IP地址，平台:', platform);
  
  try {
    const networkInterfaces = os.networkInterfaces();
    const ipAddresses = [];
    
    // 遍历所有网络接口
    for (const [interfaceName, addresses] of Object.entries(networkInterfaces)) {
      if (!addresses) continue;
      
      for (const address of addresses) {
        // 跳过内部（loopback）和非IPv4地址
        if (address.internal || address.family !== 'IPv4') {
          continue;
        }
        
        ipAddresses.push({
          interface: interfaceName,
          address: address.address,
          netmask: address.netmask,
          mac: address.mac || null
        });
      }
    }
    
    // 按接口名称排序
    ipAddresses.sort((a, b) => {
      // 优先显示以太网和WiFi接口
      const priority = (name) => {
        const lower = name.toLowerCase();
        if (lower.includes('ethernet') || lower.includes('eth')) return 1;
        if (lower.includes('wifi') || lower.includes('wlan') || lower.includes('airport')) return 2;
        if (lower.includes('en0') || lower.includes('en1')) return 3;
        return 4;
      };
      return priority(a.interface) - priority(b.interface);
    });
    
    // 获取主机名
    const hostname = os.hostname();
    
    // 尝试获取公网IP（可选，需要网络请求）
    let publicIP = null;
    try {
      // 使用多个服务尝试获取公网IP
      const publicIPServices = [
        'https://api.ipify.org?format=json',
        'https://api.ip.sb/ip',
        'https://ifconfig.me/ip'
      ];
      
      for (const service of publicIPServices) {
        try {
          const https = require('https');
          const http = require('http');
          const url = require('url');
          
          const parsedUrl = new URL(service);
          const client = parsedUrl.protocol === 'https:' ? https : http;
          
          const result = await new Promise((resolve, reject) => {
            const req = client.get(service, (res) => {
              let data = '';
              res.on('data', (chunk) => { data += chunk; });
              res.on('end', () => {
                try {
                  const json = JSON.parse(data);
                  resolve(json.ip || data.trim());
                } catch (e) {
                  resolve(data.trim());
                }
              });
            });
            req.on('error', reject);
            req.setTimeout(3000, () => {
              req.destroy();
              reject(new Error('Timeout'));
            });
          });
          
          if (result && /^\d+\.\d+\.\d+\.\d+$/.test(result)) {
            publicIP = result;
            console.log('获取到公网IP:', publicIP);
            break;
          }
        } catch (error) {
          console.warn(`从${service}获取公网IP失败:`, error.message);
          continue;
        }
      }
    } catch (error) {
      console.warn('获取公网IP失败:', error.message);
    }
    
    return {
      hostname: hostname,
      interfaces: ipAddresses,
      publicIP: publicIP,
      platform: platform
    };
  } catch (error) {
    console.error('获取IP地址失败:', error);
    return {
      hostname: os.hostname(),
      interfaces: [],
      publicIP: null,
      platform: platform,
      error: error.message
    };
  }
}

// 获取IP地址
ipcMain.handle('get-ip-addresses', async (event) => {
  console.log('收到获取IP地址请求');
  try {
    const ipInfo = await getIPAddresses();
    console.log('IP地址信息:', ipInfo);
    return ipInfo;
  } catch (error) {
    console.error('获取IP地址错误:', error);
    return {
      hostname: os.hostname(),
      interfaces: [],
      publicIP: null,
      platform: process.platform,
      error: error.message
    };
  }
});

// 创建悬浮窗
ipcMain.on('create-float-window', (event) => {
  // 检查主窗口是否存在
  if (!mainWindow || mainWindow.isDestroyed()) {
    console.error('创建悬浮窗失败: 主窗口不可用');
    if (event.reply) {
      event.reply('window-creation-error', 'Main window not available');
  }
    return;
  }

  try {
    const floatWindow = new BrowserWindow({
      windowInfo: {
        // type的取值是mainWindow，subWindow，floatWindow
        // 创建floatWindow，同时parent应设置为父窗口引用
        type: 'floatWindow'
      },
      width: 400,
      height: 300,
      parent: mainWindow,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
      },
    });
    
    const windowId = floatWindow.id;
    floatWindows.set(windowId, floatWindow);
    
    floatWindow.loadFile('sub.html');
    
    floatWindow.on('closed', () => {
      floatWindows.delete(windowId);
      console.log('悬浮窗已关闭:', windowId);
    });
    
    // 错误处理
    floatWindow.webContents.on('crashed', () => {
      console.error('悬浮窗崩溃:', windowId);
      floatWindows.delete(windowId);
    });
    
    floatWindow.webContents.on('render-process-gone', (event, details) => {
      console.error('悬浮窗渲染进程崩溃:', windowId, details);
      floatWindows.delete(windowId);
    });
    
    console.log('悬浮窗创建成功:', windowId);
  } catch (error) {
    console.error('创建悬浮窗失败:', error);
    if (event.reply) {
      event.reply('window-creation-error', error.message);
    }
  }
});

// 创建浏览器窗口
ipcMain.handle('create-browser-window', async (event, initialUrl) => {
  console.log('收到创建浏览器窗口请求，初始URL:', initialUrl);
  
  // 检查主窗口是否存在
  if (!mainWindow || mainWindow.isDestroyed()) {
    console.error('创建浏览器窗口失败: 主窗口不可用');
    return { success: false, error: 'Main window not available' };
  }

  try {
    const browserWindow = new BrowserWindow({
      width: 1200,
      height: 800,
      minWidth: 600,
      minHeight: 400,
      parent: mainWindow,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: true, // 启用Web安全
        webviewTag: true, // 启用webview标签
      },
      title: '应用内浏览器',
      show: false, // 先不显示，等加载完成后再显示
    });
    
    const windowId = browserWindow.id;
    browserWindows.set(windowId, browserWindow);
    
    // 加载浏览器页面
    const url = initialUrl || 'https://www.openharmony.cn';
    browserWindow.loadFile('browser.html', { query: { url: url } });
    
    // 窗口准备好后显示
    browserWindow.once('ready-to-show', () => {
      browserWindow.show();
      console.log('浏览器窗口已显示:', windowId);
    });
    
    // 窗口关闭时清理引用
    browserWindow.on('closed', () => {
      browserWindows.delete(windowId);
      console.log('浏览器窗口已关闭:', windowId);
    });
    
    // 监听页面标题变化
    browserWindow.webContents.on('page-title-updated', (event, title) => {
      browserWindow.setTitle(title || '应用内浏览器');
      // 发送标题更新到渲染进程
      browserWindow.webContents.send('page-title-updated', title);
    });
    
    // 监听URL变化
    browserWindow.webContents.on('did-navigate', (event, url) => {
      browserWindow.webContents.send('url-changed', url);
    });
    
    browserWindow.webContents.on('did-navigate-in-page', (event, url) => {
      browserWindow.webContents.send('url-changed', url);
    });
    
    // 监听加载状态
    browserWindow.webContents.on('did-start-loading', () => {
      browserWindow.webContents.send('loading-state-changed', { loading: true });
    });
    
    browserWindow.webContents.on('did-stop-loading', () => {
      browserWindow.webContents.send('loading-state-changed', { loading: false });
    });
    
    // 错误处理
    browserWindow.webContents.on('crashed', () => {
      console.error('浏览器窗口崩溃:', windowId);
      browserWindows.delete(windowId);
    });

    browserWindow.webContents.on('render-process-gone', (event, details) => {
      console.error('浏览器窗口渲染进程崩溃:', windowId, details);
      browserWindows.delete(windowId);
    });
    
    // 处理新窗口请求（在新标签页中打开）
    browserWindow.webContents.setWindowOpenHandler(({ url }) => {
      // 在同一个窗口中导航到新URL
      browserWindow.webContents.loadURL(url);
      return { action: 'deny' };
    });
    
    console.log('浏览器窗口创建成功:', windowId);
    return { success: true, windowId: windowId };
  } catch (error) {
    console.error('创建浏览器窗口失败:', error);
    return { success: false, error: error.message };
  }
});

// 浏览器窗口导航
ipcMain.handle('browser-navigate', async (event, windowId, url) => {
  const browserWindow = browserWindows.get(windowId);
  if (!browserWindow || browserWindow.isDestroyed()) {
    return { success: false, error: 'Browser window not found' };
  }
  
  try {
    await browserWindow.webContents.loadURL(url);
    return { success: true };
  } catch (error) {
    console.error('导航失败:', error);
    return { success: false, error: error.message };
  }
});

// 浏览器窗口前进/后退/刷新
ipcMain.handle('browser-go-back', async (event, windowId) => {
  const browserWindow = browserWindows.get(windowId);
  if (!browserWindow || browserWindow.isDestroyed()) {
    return { success: false, error: 'Browser window not found' };
  }
  
  if (browserWindow.webContents.canGoBack()) {
    browserWindow.webContents.goBack();
    return { success: true };
  }
  return { success: false, error: 'Cannot go back' };
});

ipcMain.handle('browser-go-forward', async (event, windowId) => {
  const browserWindow = browserWindows.get(windowId);
  if (!browserWindow || browserWindow.isDestroyed()) {
    return { success: false, error: 'Browser window not found' };
  }
  
  if (browserWindow.webContents.canGoForward()) {
    browserWindow.webContents.goForward();
    return { success: true };
  }
  return { success: false, error: 'Cannot go forward' };
});

ipcMain.handle('browser-reload', async (event, windowId) => {
  const browserWindow = browserWindows.get(windowId);
  if (!browserWindow || browserWindow.isDestroyed()) {
    return { success: false, error: 'Browser window not found' };
  }
  
  browserWindow.webContents.reload();
  return { success: true };
});

app.whenReady().then(() => {
  // 检查通知是否支持
  if (Notification.isSupported()) {
    console.log('通知功能已支持');
    console.log('平台:', process.platform);
    
    // macOS 特殊处理：确保应用在 Dock 中
    if (process.platform === 'darwin') {
      // macOS 上，Electron 应用默认会在 Dock 中
      // 但我们可以确保应用可见
      if (app.dock) {
        app.dock.show().catch(err => {
          console.log('Dock 显示（可选）:', err.message);
        });
        
        // 测试通知功能（可选，用于调试）
        setTimeout(() => {
          const testNotification = new Notification({
            title: '坚果通知',
            body: '这是来自坚果的通知'
          });
          testNotification.show();
        }, 2000);
      } else {
        console.warn('app.dock 不可用，可能影响 macOS 通知显示');
      }
    }
  } else {
    console.warn('通知功能不支持');
    console.warn('请检查系统通知设置');
  }
  
  createWindow();
});

app.on('window-all-closed', () => {
  // 清理所有窗口引用
  subWindows.clear();
  floatWindows.clear();
  browserWindows.clear();
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
